import prompt from '../utils/prompt.js';

// 请求回调处理
const interceptor = (res, url, config) => {
  switch (res.statusCode) {
  case 200:
    if (config.responseType === 'arraybuffer') {
      return {
        data: res.data,
        header: res.header
      };
    } else {
      if (res.data.retCode === '0') {
        if (config.needHeader) { // 是否需要返回header
          return {
            header: res.header,
            data: res.data
          };
        } else {
          return res.data;
        }
      } else {
        if (!config.noModal) {
          prompt.showModal(res.data.retMsg);
        } else {
          return res.data;
        }
      }
    }
    break;
  case 404: prompt.showToast(`未知的请求地址 ${url}`); break;
  case 401: prompt.showToast('鉴权信息异常'); break;
  default:
    prompt.showToast('网络异常，请稍后再试');
    break;
  }
};

// 请求异常处理
const failInterceptor = (err) => {
  console.error(err);
};

const http = {
  hostPots: 'https://devin.cool/csc',
  header: {
    'content-type': 'application/json'
  },
  dataType: 'json',
  responseType: 'text', // text, arraybuffer
  timeout: 30000,
  requestCount: 0,


  complete (config) {
    let loading = config.loading === undefined ? true : config.loading;
    if (loading) {
      this.requestCount--;
      if (this.requestCount <= 0) {
        wx.hideLoading();
      }
    }
  },

  prev (config) {
    let loading = config.loading === undefined ? true : config.loading;
    if (loading) {
      wx.showLoading({
        title: '处理中',
        mask: true
      });
      this.requestCount++;
    }
  },

  // get请求
  get (url, data, config = {}) {
    return new Promise((resolve, reject) => {
      this.prev(config);
      wx.request({
        url: `${this.hostPots}${url}`,
        data,
        header: { ...this.header, ...config.header },
        method: 'GET',
        dataType: config.dataType || this.dataType,
        responseType: config.responseType || this.responseType,
        timeout: this.timeout,
        success: (result) => {
          resolve(interceptor(result, url, config));
        },
        fail: err => {
          failInterceptor(err);
          reject(err);
        },
        complete: () => {
          this.complete(config);
        }
      });
    });
  },

  // post 请求
  post (url, data, config = {}) {
    if (config.urlParam) {
      for (const key of Object.keys(data)) {
        if (url.indexOf('?') > -1) {
          url += `&${key}=${data[key]}`;
        } else {
          url += `?${key}=${data[key]}`;
        }
      }
    }
    return new Promise((resolve, reject) => {
      this.prev(config);
      wx.request({
        url: `${this.hostPots}${url}`,
        data,
        header: { ...this.header, ...config.header },
        method: 'POST',
        dataType: config.dataType || this.dataType,
        responseType: config.responseType || this.responseType,
        timeout: this.timeout,
        success: (result) => {
          resolve(interceptor(result, url, config));
        },
        fail: err => {
          failInterceptor(err);
          reject(err);
        },
        complete: () => {
          this.complete(config);
        }
      });
    });
  }

};

export default http;